//
//  WXEmotionViewModel.swift
//  weibo
//
//  Created by 王旭 on 16/4/28.
//  Copyright © 2016年 王旭. All rights reserved.
//

import UIKit

//表情键盘行数
let EmotionKeyboardRow = 3
//表情键盘列数
let EmotionKeyboardCol = 7
//一页表情个数
let EmotionKeyboardCount = EmotionKeyboardRow * EmotionKeyboardCol - 1

class WXEmotionViewModel: NSObject {
    
    /// 最近表情数组
    lazy var recentEmoticons: [WXEmotionModel] = {
        // 从沙盒里面去取
        if let result = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? [WXEmotionModel] {
            return result
        }else{
            return  [WXEmotionModel]()
        }
    }()
    
    //归档路径
    private lazy var path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("recentEmoticon.archive")

    //单例
    static let sharedEmotionViewModel :WXEmotionViewModel = WXEmotionViewModel()
    //保存最近表情
    func saveRecentEmoticon(emoticon: WXEmotionModel){
        
        var emoticons = allArr[0][0]
        //--------------------以下不推荐-----------------
        // 去重
        //        for (index,value) in emoticons.enumerate() {
        //            if value.type == emoticon.type {
        //                if value.type == "1" {
        //                    // emoji表情，对比code
        //                    if value.code == emoticon.code {
        //                        // 表情是一样的？？
        //                        emoticons.removeAtIndex(index)
        //                    }
        //                }else{
        //                    // 对比chs
        //                    if value.chs == emoticon.chs {
        //                        // 表情是一样的
        //                        emoticons.removeAtIndex(index)
        //                    }
        //                }
        //            }
        //        }
        //--------------------以上不推荐-----------------
        
        // 取到的重复表情的数组
        let repeatEmoticon = emoticons.filter { (value) -> Bool in
            if value.type == emoticon.type {
                if value.type == "1" {
                    // emoji表情，对比code
                    return value.code == emoticon.code
                }else{
                    // 对比chs
                    return value.chs == emoticon.chs
                }
            }else{
                return false
            }
        }
        
        // 移除重复移
        for value in repeatEmoticon {
            if let index = emoticons.indexOf(value) {
                emoticons.removeAtIndex(index)
            }
        }
    
        // 1. 将传入的表情模型保存到当前的最近表情的数组里面去
        // self.recentEmoticons.append(emoticon)
//        allArr[0][0].insert(emoticon, atIndex: 0)
        emoticons.insert(emoticon, atIndex: 0)
        
        // 2. 去重 & 去掉多余20个的表情
        while emoticons.count > 20 {
            emoticons.removeLast()
        }
        
        allArr[0][0] = emoticons
        
        // 3. 使用归档的方法保存最近表情的数组
        //--------------------以下为测试代码-----------------
        //        print(path)
        //--------------------以上为测试代码-----------------
        NSKeyedArchiver.archiveRootObject(emoticons, toFile: path)
        
    }
    
    //通过表情字符串找到其对应的表情模型
    func emoticonWithChs(chs: String) -> WXEmotionModel? {
        
        /// 遍历默认表情
        for value in defaultArr {
            if value.chs == chs {
                return value
            }
        }
        
        /// 遍历浪小花表情
        for value in lxhArr {
            if value.chs == chs {
                return value
            }
        }
        
        return nil
    }
    
    //把表情数组转换为collectionView需要的二级数组
    private func emotionSectionArray(emotions:[WXEmotionModel])->[[WXEmotionModel]] {
        //1.计算页数
        let pageCount = (emotions.count - 1) / 20 + 1
        //2.定义二级数组接收
        var emotionSectionArray : [[WXEmotionModel]] = [[WXEmotionModel]]()
        //3.分割传入的表情数组->二级数组
        for i in 0..<pageCount {
            //截取位置
            let loc = 20 * i
            //截取长度
            var len = 20
            //当剩余数组元素小于截取长度
            if emotions.count - loc < len {
                len = emotions.count - loc
            }
            
            //截取
            let emotionItemArray = (emotions as NSArray).subarrayWithRange(NSMakeRange(loc, len)) as! [WXEmotionModel]
            
            //拼接二级数组
            emotionSectionArray.append(emotionItemArray)
        }
        //返回
        return emotionSectionArray
    }
    
    //根据路径获得表情数组
    private func emotionsWithPath(filePath:String)->[WXEmotionModel] {
        //1.获得表情路径
        let path = emotionBundel.pathForResource(filePath, ofType: nil)!
        //2.读取到数组
        let array = NSArray(contentsOfFile: path)!
        //3.定义临时数组
        var tempArr = [WXEmotionModel]()
        //4.字典转模型
        for value in array {
            let model = WXEmotionModel(dic: value as! [String : AnyObject])
            
            
            let folderName =  (filePath as NSString).stringByDeletingLastPathComponent
            model.folderName = folderName
            
            tempArr.append(model)
        }
        //5.返回对应的数组
        return tempArr
    }
    
    //懒加载三级表情数组
    @objc lazy var allArr :[[[WXEmotionModel]]] = [
        [self.recentEmoticons],
        self.emotionSectionArray(self.defaultArr),
        self.emotionSectionArray(self.emojiArr),
        self.emotionSectionArray(self.lxhArr),
    ]
    
    //懒加载默认表情数组
    private lazy var defaultArr :[WXEmotionModel] = {
        return self.emotionsWithPath("default/info.plist")
    }()
    //懒加载emoji表情数组
    private lazy var emojiArr :[WXEmotionModel] = {
       return self.emotionsWithPath("emoji/info.plist")
    }()
    //懒加载浪小花表情数组
    private lazy var lxhArr :[WXEmotionModel] = {
        return self.emotionsWithPath("lxh/info.plist")
    }()
    
    //懒加载表情bundle
    lazy var emotionBundel :NSBundle = {
       let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        return NSBundle(path: path)!
    }()

}
